import json
import time
import webapp2

from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, diverse_operations

from wtforms.ext.appengine.db import model_form
from wtforms.fields import TextField
from wtforms import validators

from common import functions

from BaseHandler import BaseHandler

class DiverseOperations(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(DiverseOperations, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'od_date': _('Date'), 'immeuble': _('Tenement'), 'subaccount_debit': _('Debit account'),
                       'subaccount_credit': _('Credit account'), 'journal': _('Journal'), 'number': _('# of item'),
                       'lable': _('Label'), 'amount': _('Amount'), 'tva': _('VAT'), 'rental_charges': _('Total rental charges'),
                       'tax_deduction': _('Tax deduction amount'), 'property_income_deduction': _('Income deduction amount')
                       }

    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        template_values = {
                           'title': _('Diverse operations. %s' % imm.name),
                           'header': _('ATENET. Diverse operations. %s' % imm.name),
                           'app_user': self.au,
                           'immeuble': imm,
                           'lurl': users.create_logout_url('/'),
                           'section': 'vie',
                           'leftmenu': 'diverse_operations',
                           'fields': self.fields
        }

        template = self.jinja2.get_template('templates/diverse_operations_list.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        query = imm.diverse_operations_set.run()
        do = []
        for d in query:
            do.append([functions.datetimeformat(d.od_date), unicode(d.subaccount_debit), unicode(d.subaccount_credit), unicode(d.journal), unicode(d.number), unicode(d.lable), d.amount, d.tva, d.rental_charges, d.tax_deduction, d.property_income_deduction, str(d.key().id())])
        ret = {}
        ret['aaData'] = do
        self.response.out.write(json.dumps(ret))
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        ok_message = ''
        subaccts = imm.get_subacc_list()
        
        DiverseOperationForm = model_form(diverse_operations, exclude=['immeuble', 'lastchange_by', 'lastchange_date'])
        setattr(DiverseOperationForm, 'subaccount_debit', TextField(u'Debit account', [validators.required(),]))
        setattr(DiverseOperationForm, 'subaccount_credit', TextField(u'Credit account', [validators.required(),]))
        DiverseOperationForm.od_date.creation_counter = 1
        DiverseOperationForm.subaccount_debit.creation_counter = 2
        DiverseOperationForm.subaccount_credit.creation_counter = 3
        DiverseOperationForm.journal.creation_counter = 4
        DiverseOperationForm.number.creation_counter = 5
        DiverseOperationForm.lable.creation_counter = 6
        DiverseOperationForm.amount.creation_counter = 7
        DiverseOperationForm.tva.creation_counter = 8
        DiverseOperationForm.rental_charges.creation_counter = 9
        DiverseOperationForm.tax_deduction.creation_counter = 10
        DiverseOperationForm.property_income_deduction.creation_counter = 11
        
        if self.request.method == 'GET':
            form = DiverseOperationForm()
            
        if self.request.method == 'POST':
            post_obj = self.request.POST
            
            exists = False
            for a in subaccts:
                name = str(a.code) + ' ' + str(a.name)
                if name == post_obj['subaccount_debit']:
                    post_obj['subaccount_debit'] = a
                    exists = True
                    break
            if exists is False:
                post_obj['subaccount_debit'] = ''
            
            exists = False
            for a in subaccts:
                name = str(a.code) + ' ' + str(a.name)
                if name == post_obj['subaccount_credit']:
                    post_obj['subaccount_credit'] = a
                    exists = True
                    break
            if exists is False:
                post_obj['subaccount_credit'] = ''
            
            form = DiverseOperationForm(post_obj)
            
            if form.validate():
                obj_do = diverse_operations(
                                  od_date = form['od_date'].data,
                                  subaccount_debit = form['subaccount_debit'].data,
                                  subaccount_credit = form['subaccount_credit'].data,
                                  journal = form['journal'].data,
                                  number = form['number'].data,
                                  lable = form['lable'].data,
                                  amount = form['amount'].data,
                                  tva = form['tva'].data,
                                  rental_charges = form['rental_charges'].data,
                                  tax_deduction = form['tax_deduction'].data,
                                  property_income_deduction = form['property_income_deduction'].data,
                                  immeuble = imm,
                                  lastchange_by = self.au
                                  )
                obj_do.put()
                while not obj_do.is_saved():
                    time.sleep(2)
                
                ok_message = _('Diverse operation was added.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        do_id = kwargs.get('do_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        subaccts = imm.get_subacc_list()
        obj_do = diverse_operations.get_by_id(int(do_id))
        
        DiverseOperationForm = model_form(diverse_operations, exclude=['immeuble', 'lastchange_by', 'lastchange_date'])
        setattr(DiverseOperationForm, 'subaccount_debit', TextField(u'Debit account', [validators.required(),]))
        setattr(DiverseOperationForm, 'subaccount_credit', TextField(u'Credit account', [validators.required(),]))
        DiverseOperationForm.od_date.creation_counter = 1
        DiverseOperationForm.subaccount_debit.creation_counter = 2
        DiverseOperationForm.subaccount_credit.creation_counter = 3
        DiverseOperationForm.journal.creation_counter = 4
        DiverseOperationForm.number.creation_counter = 5
        DiverseOperationForm.lable.creation_counter = 6
        DiverseOperationForm.amount.creation_counter = 7
        DiverseOperationForm.tva.creation_counter = 8
        DiverseOperationForm.rental_charges.creation_counter = 9
        DiverseOperationForm.tax_deduction.creation_counter = 10
        DiverseOperationForm.property_income_deduction.creation_counter = 11
        
        if self.request.method == 'GET':
            form = DiverseOperationForm(obj=obj_do)
            
        if self.request.method == 'POST':
            post_obj = self.request.POST
            
            exists = False
            for a in subaccts:
                name = str(a.code) + ' ' + str(a.name)
                if name == post_obj['subaccount_debit']:
                    post_obj['subaccount_debit'] = a
                    exists = True
                    break
            if exists is False:
                post_obj['subaccount_debit'] = ''
            
            exists = False
            for a in subaccts:
                name = str(a.code) + ' ' + str(a.name)
                if name == post_obj['subaccount_credit']:
                    post_obj['subaccount_credit'] = a
                    exists = True
                    break
            if exists is False:
                post_obj['subaccount_credit'] = ''
            
            form = DiverseOperationForm(post_obj)
            if form.validate():
                form.populate_obj(obj_do)
                obj_do.put()
                
                ok_message = _('Diverse operation was updated.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
